﻿using EpubFactory.Common;
using EpubFactory.Template;
using EpubFactory.Template.V201;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.IO.Compression;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace EpubFactory.Winform
{
    public partial class MainForm : Form
    {
        public MainForm()
        {
            InitializeComponent();
        }
        private Book book;

        private void btnImport_Click(object sender, EventArgs e)
        {
            if (book == null)
            {
                book = new Book()
                {
                    Chapters = new List<Chapter>()
                };
            }
            OpenFileDialog ofdChooseFiles = new OpenFileDialog();
            ofdChooseFiles.Multiselect = true;
            //ofdChooseFiles.InitialDirectory = pathcsv;
            //设置文件名
            //ofd_list.FileName = "";
            //设置文件类型
            ofdChooseFiles.Filter = "*.txt (*.txt)|*.txt|*.html (*.html)|*.html|所有文件|*.*";
            //设置文件类型索引

            if (ofdChooseFiles.ShowDialog() == DialogResult.OK)
            {
                int t = book.Chapters.Count;
                lvChapterList.BeginUpdate();
                foreach (var filePath in ofdChooseFiles.FileNames)
                {
                    book.Chapters.Add(new Chapter()
                    {
                        FilePath = filePath,
                        SortOrder = t
                    });
                    var item = new ListViewItem(book.Chapters.Last().FileName)
                    {

                    };
                    item.SubItems.Add(string.Empty);
                    item.SubItems.Add(t.ToString());
                    lvChapterList.Items.Add(item);
                    t++;
                }
                lvChapterList.EndUpdate();

            }
        }

        private void btnGenerateTitle_Click(object sender, EventArgs e)
        {
            Parallel.ForEach(book.Chapters, chapter =>
            {
                using (var file = new StreamReader(chapter.FilePath, Encoding.Default))
                {
                    if (!file.EndOfStream)
                    {
                        chapter.Title = file.ReadLine();
                        chapter.Content = "<p>" + file.ReadToEnd().Trim().Replace("<br>", "").Replace(Environment.NewLine, "</p><p>") + "</p>";
                    }
                }
            });
            lvChapterList.BeginUpdate();
            int i = 0;
            foreach (ListViewItem item in lvChapterList.Items)
            {
                item.SubItems[1].Text = book.Chapters[i].Title;
                i++;
            }
            lvChapterList.EndUpdate();
        }

        private void btnGenerateEpub_Click(object sender, EventArgs e)
        {
            if (book == null)
            {
                book = new Book();
            }
            book.Title = txtTitle.Text;
            book.Authors = new List<string>() { txtAuthor.Text };
            book.CoverUrl = txtCoverUrl.Text;
            book.Subject = string.Empty;
            book.Summary = string.Empty;
            var baseDir = Path.Combine("Books", book.Title);
            if (!Directory.Exists(baseDir))
            {
                Directory.CreateDirectory(baseDir);
            }
            /*
            if (!Directory.Exists("Books"))
            {
                Directory.CreateDirectory("Books");
            }
            if (!Directory.Exists(Path.Combine("Books", book.Title)))
            {
                Directory.CreateDirectory(Path.Combine("Books", book.Title));
            }
             * */
            var epubFileName = book.Title + ".epub";
            var epubFilePath = Path.Combine(baseDir, epubFileName);
            if (File.Exists(epubFilePath))
            {
                File.Delete(epubFilePath);
            }
            File.Copy(Path.Combine("Tpl", "default.zip"), epubFilePath);
            book.GenerateChaptersId();
            using (ZipArchive archive = ZipFile.Open(epubFilePath, ZipArchiveMode.Update))
            {
                ZipArchiveEntry opfEntry = archive.CreateEntry("OPS/content.opf");
                using (StreamWriter writer = new StreamWriter(opfEntry.Open()))
                {
                    var opf = new ContentOPFTemplate(book);
                    writer.Write(opf.TransformText());
                }
                ZipArchiveEntry tocEntry = archive.CreateEntry("OPS/toc.ncx");

                using (StreamWriter writer = new StreamWriter(tocEntry.Open()))
                {
                    var toc = new TocNcxTemplate(book);
                    writer.Write(toc.TransformText());
                }
                if (!string.IsNullOrWhiteSpace(book.CoverUrl) && File.Exists(book.CoverUrl))
                {

                    ZipArchiveEntry coverEntry = archive.GetEntry("OPS/images/cover.jpg");
                    coverEntry.Delete();
                    archive.CreateEntryFromFile(book.CoverUrl, "OPS/images/cover.jpg");
                    /*
                    using (StreamWriter writer = new StreamWriter(coverEntry.Open()))
                    {                    
                        writer.Write(File.ReadAllBytes(book.CoverUrl));
                    }
                     * */
                }

                ZipArchiveEntry chapterContentTemplateEntry = archive.GetEntry("OPS/chapter-template.html");
                string chapterContentTemplate = null;
                using (StreamReader reader = new StreamReader(chapterContentTemplateEntry.Open()))
                {
                    chapterContentTemplate = reader.ReadToEnd();
                }

                foreach (var chapter in book.Chapters)
                {
                    ZipArchiveEntry chapterEntry = archive.CreateEntry("OPS/" + chapter.Id + ".html");
                    using (StreamWriter writer = new StreamWriter(chapterEntry.Open()))
                    {
                        writer.Write(chapterContentTemplate.Replace(@"\{title}", chapter.Title).Replace(@"\{body}", chapter.Content));
                    }
                }
            }
            MessageBox.Show("生成成功");
        }

        private void btnChooseCover_Click(object sender, EventArgs e)
        {
            OpenFileDialog ofdChooseFiles = new OpenFileDialog();
            ofdChooseFiles.Multiselect = false;
            //ofdChooseFiles.InitialDirectory = pathcsv;
            //设置文件名
            //ofd_list.FileName = "";
            //设置文件类型
            ofdChooseFiles.Filter = "*.jpg (*.jpg)|*.jpg|*.png (*.png)|*.png|所有文件|*.*";
            //设置文件类型索引

            if (ofdChooseFiles.ShowDialog() == DialogResult.OK)
            {
                txtCoverUrl.Text = ofdChooseFiles.FileName;
            }
        }
    }
}
